//
//  KTLemonPaymentViewController.m
//  BoWuGuan
//
//  Created by 梁尚嘉 on 2016/12/12.
//  Copyright © 2016年 KT. All rights reserved.
//

#import "KTLemonPaymentViewController.h"
#import "KTPaySelectionTableCell.h"
#import "KTPayUtils.h"
#import "WXPayConfig.h"

#import "OMPaymentResponse.h"
#import "OMPaymentInfoTableCell.h"
#import "OMPaymentSelectionTableCell.h"
@interface KTLemonPaymentViewController ()
@property (nonatomic, strong, readwrite) UIButton     *confirmButton;
@property (nonatomic, strong) NSArray *selections;
@property (nonatomic, strong) NSMutableDictionary *selectionResults;
@property (nonatomic, assign) BOOL isShow;
@property (nonatomic, strong) OMPaymentResponse *paymentResponse;
@end

@implementation KTLemonPaymentViewController

- (void)viewDidLoad {
    _selections =   @[
                      @{@"icon":@"icon_wx_paySelection",@"title":@"微信支付",@"description":@"推荐安装微信5.0及以上版本使用"},
                      @{@"icon":@"icon_alipay_paySelection",@"title":@"支付宝",@"description":@"推荐有支付宝账号的用户使用"},
                      ];
    _selectionResults = [@{
                           [NSIndexPath indexPathForRow:0 inSection:1]:@(YES),
                           [NSIndexPath indexPathForRow:0 inSection:1]:@(NO),
                           }mutableCopy];

    [super viewDidLoad];

    self.fd_interactivePopDisabled = YES;

    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        make.top.equalTo(self.navigationBar.mas_bottom);
    }];

    UIView *footer = [UIView new];
    footer.backgroundColor = SM_whiteColor;
    [self.view addSubview:footer];
    [footer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.tableView.mas_bottom);
        make.height.equalTo(@(SM_SIZE(130)));
        make.left.right.bottom.equalTo(@0);
    }];
    [footer addSubview:self.confirmButton];
    [self.confirmButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(@(SM_SIZE(20)));
        make.right.bottom.equalTo(@(SM_SIZE(-20)));
    }];
    UIView *line = [UIView new];
    line.backgroundColor = SM_naviShadowColor;
    [footer addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(@0);
        make.height.equalTo(@(.5f));
    }];


    // Do any additional setup after loading the view.

    [self observeSetup];
    [self getPaymentInfo];

    paymentSelectionCell = [OMPaymentSelectionTableCell tableViewCellWithTableView:self.tableView];
}

- (void)reloadDataFromNetWork
{
    [self getPaymentInfo];
}

- (void)getPaymentInfo
{
    [self startAnimating:true];
    [KTHttpUtils
     GET_NOCACHE:@"order/payment.jhtml"
     parameters:@{@"sn":self.order.sn}
     progress:nil
     completion:^(id responseObject, BOOL isSuccess, NSString *message) {
         if (isSuccess) {
             OMPaymentResponse *paymentResponse = [OMPaymentResponse mj_objectWithKeyValues:responseObject[OMDatumKey]];
             for (OMPaymentPlugin *plugin in paymentResponse.paymentPlugins) {
                 plugin.logo = [responseObject[OMImagePrefix]?:@"" stringByAppendingString:plugin.logo];
             }
             self.paymentResponse = paymentResponse;
             [self startAnimating:NO];
         }else {
             [self showNetWorkError];
         }
    }];
}

- (void)setPaymentResponse:(OMPaymentResponse *)paymentResponse
{
    _paymentResponse = paymentResponse;
    self.order.amount = paymentResponse.amount;
    [paymentSelectionCell configureCellWithObj:self.paymentResponse];
    [self.tableView reloadData];
}

- (void)observeSetup
{
    @weakify(self);
    [SMNotificationMonitorRACSignal(SM_WXPaySuccessNotification) subscribeNext:^(id x) {
        @strongify(self);
        if (!self.isShow) {
            self.isShow = YES;
            [self checkPayResultWithType:KTPayWithWechat];

        }
    }];


    [SMNotificationMonitorRACSignal(SM_AliPaySuccessNotification) subscribeNext:^(id x) {
        @strongify(self);
        if (!self.isShow) {
            self.isShow = YES;
            [self checkPayResultWithType:KTPayWithAliPay];
        }
    }];
}


/**
 支付请求调用

 @param payWay 支付方式
 */
- (void)checkPayResultWithType:(KTPayWay)payWay
{
    @weakify(self);
    [OMHUD HUDShieldLoading:@"正在查询支付结果"];
    [KTHttpUtils GET:@"payment/payResult.jhtml"
          parameters:@{@"sn":self.order.sn}
            progress:nil
          completion:^(id responseObject, BOOL isSuccess, NSString *message) {
              @strongify(self);
              if (isSuccess)
              {
                  OMOrder *order = [OMOrder mj_objectWithKeyValues:responseObject[OMDatumKey]];
                  self.order.status = order.status;

                  if (self.order.status != pendingPayment) {
                      [self payResultSuccessHandlerWithPayWay:payWay];
                  }else {
                      [self payResultErrorHandlerWithPayWay:payWay];
                  }
              }
              else {
                  [self payResultErrorHandlerWithPayWay:payWay];
              }
          }];
}

- (void)payResultSuccessHandlerWithPayWay:(KTPayWay)payWay
{
    self.isShow = NO;
    [OMHUD HUDHide];
    NaviPush(@"OMPaySuccessViewController", @{@"order":self.order});
//    [KTAlertView alertWithMessage:@"支付成功!"
//                            Title:@"提示"
//                     ButtonTitles:nil
//                   withClickBlock:^(NSUInteger indexOfButton) {
//
//                       self.isShow = NO;
//                       [self backAction];
//                       [OMHUD HUDHide];
//                   }];
}

- (void)payResultErrorHandlerWithPayWay:(KTPayWay)payWay
{
    [KTAlertView alertWithMessage:@"支付结果查询失败,请到下单记录中查看结果，勿要重复支付"
                            Title:@"提示"
                     ButtonTitles:@[@"重试"]
                   withClickBlock:^(NSUInteger indexOfButton) {
                       if (indexOfButton == 1) {
                           [self checkPayResultWithType:payWay];
                       }else {
                           [self backAction];
                           [KTAlertView alertWithMessage:@"请在我的订单查看订单的付款状态。您若已支付，请勿重复支付；若有疑问，请联系客服。对您造成的不便，我们表示深深的谦意！"
                                                   Title:nil
                                            ButtonTitles:nil
                                          withClickBlock:nil];
                           [OMHUD HUDHide];
                       }
                       self.isShow = NO;
                   }];
}

- (void)backAction
{
    @weakify(self);
    [KTAlertView alertWithMessage:@"取消支付后，您还可以返回到我的订单，找到对应的订单进行支付"
                            Title:@"确定取消支付吗?"
                     ButtonTitles:@[@"确定"]
                   withClickBlock:^(NSUInteger indexOfButton) {
                       @strongify(self);
                       if (indexOfButton) {
                           if (self.isRepay) {
                               [super backAction];
                           }else
                               NaviPopToRoot(YES);
                       }
    }];
}

#pragma mark - tableView delegate && datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (!self.paymentResponse) {
        return 0;
    }
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

OMPaymentSelectionTableCell *paymentSelectionCell = nil;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        OMPaymentInfoTableCell *cell = [OMPaymentInfoTableCell tableViewCellWithTableView:self.tableView];
        [cell configureCellWithObj:self.paymentResponse];
        return cell;
    }else if (indexPath.section == 1) {
        return paymentSelectionCell;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        for (id<NSCopying> key in self.selectionResults.allKeys) {
            [self.selectionResults setObject:@(NO) forKey:key];
        }
        [self.selectionResults setObject:@(YES) forKey:indexPath];
        [self.tableView reloadData];
    }

}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return @[@"  合计",@"  支付工具"][section];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return SM_SIZE(20);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return SM_SIZE(80);
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return [OMPaymentInfoTableCell cellHeight];
    }else if (indexPath.section == 1) {
        return [OMPaymentSelectionTableCell cellHeightWithObj:self.paymentResponse];
    }
    return DBL_EPSILON;
}

#pragma mark - Getters
- (UIButton *)confirmButton
{
    if (!_confirmButton) {
        _confirmButton = [UIButton new];
        [_confirmButton setTitle:@"去付款" forState:UIControlStateNormal];
        [_confirmButton setTitleColor:SM_blackColor forState:UIControlStateNormal];
        [_confirmButton setBackgroundImage:[UIImage imageWithColor:SM_sangouColor] forState:UIControlStateNormal];
        [_confirmButton setBackgroundImage:[UIImage imageWithColor:RGBACOLOR(0, 0, 0, .26)] forState:UIControlStateDisabled];
        _confirmButton.titleLabel.font = SM_CFont(35);
        [_confirmButton addTarget:self action:@selector(submitAction:) forControlEvents:UIControlEventTouchUpInside];
        _confirmButton.layer.cornerRadius = 4.f;
        _confirmButton.clipsToBounds = true;
    }
    return _confirmButton;
}

#pragma mark - Actions
- (void)submitAction:(UIButton *)button
{

    //安全性检测
    if (!_order) {
        [OMHUD HUDInfo:@"订单不存在!"];
        return;
    }

    //请求支付
    if ([paymentSelectionCell.selectedPaymentPluginId isEqualToString:@"weixinAppPaymentPlugin"]) {
        [OMHUD HUDShieldLoading:@"正在支付"];
        [KTPayUtils WXPayWithOrder:_order
                   paymentPluginId:paymentSelectionCell.selectedPaymentPluginId
                      onCompletion:^(BOOL success) {
            success?[OMHUD HUDHide]:[OMHUD HUDError:@"支付失败"];
        }];
    }else {
        [OMHUD HUDShieldLoading:@"正在支付"];
        [KTPayUtils AlipayWithOrder:_order
                    paymentPluginId:paymentSelectionCell.selectedPaymentPluginId
                       onCompletion:^(BOOL success) {
            success?[OMHUD HUDHide]:[OMHUD HUDError:@"支付失败"];
        }];
    }
}

@end
